// import dayjs from 'dayjs'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useSupabaseCoupleStore } from '@/store/supabaseCouple'
import { momentsService, commentsService } from '@/services/supabase'

export interface MomentImage {
  url: string
  name?: string
  size?: number
}

export interface Moment {
  id: string
  content: string
  images: MomentImage[]
  createTime: string
  user: {
    id: string
    name: string
    avatar: string
  }
}

export const useMomentsStore = defineStore('moments', () => {
  const moments = ref<Moment[]>([])
  const loading = ref(false)
  const comments = ref<Record<string, { id: string, momentId: string, userId: string, content: string, createdAt: string, userName?: string, userAvatar?: string }[]>>({})

  async function load() {
    const coupleStore = useSupabaseCoupleStore()
    if (!coupleStore)
      return
    loading.value = true
    try {
      const list = await momentsService.getByCouple(coupleStore.currentCoupleId)
      moments.value = list
    }
    finally {
      loading.value = false
    }
  }

  async function loadComments(momentId: string) {
    comments.value[momentId] = await commentsService.listByMoment(momentId)
  }

  async function addComment(momentId: string, content: string) {
    const coupleStore = useSupabaseCoupleStore()
    let userId = (uni.getStorageSync('whoAmI_userId') as string) || ''
    if (!userId)
      userId = coupleStore.profile?.user1.id || coupleStore.profile?.user2.id || ''
    const created = await commentsService.create(momentId, { userId, content })
    if (!comments.value[momentId])
      comments.value[momentId] = []
    comments.value[momentId].push(created)
    return created
  }

  async function createMoment(content: string, images: MomentImage[]) {
    const coupleStore = useSupabaseCoupleStore()
    // 优先使用 whoAmI_userId（本地身份）
    let userId = (uni.getStorageSync('whoAmI_userId') as string) || ''
    if (!userId) {
      // 兜底：从 coupleStore 取一个
      userId = coupleStore.profile?.user1.id || coupleStore.profile?.user2.id || ''
    }
    const created = await momentsService.create(coupleStore.currentCoupleId, { userId, content, images })
    moments.value.unshift(created)
    return created
  }

  async function updateMoment(id: string, updates: { content?: string, images?: MomentImage[] }) {
    const updated = await momentsService.update(id, updates)
    const idx = moments.value.findIndex(m => m.id === id)
    if (idx !== -1)
      moments.value[idx] = updated
    return updated
  }

  async function removeMoment(id: string) {
    await momentsService.remove(id)
    const idx = moments.value.findIndex(m => m.id === id)
    if (idx !== -1)
      moments.value.splice(idx, 1)
  }

  return {
    moments,
    loading,
    load,
    createMoment,
    updateMoment,
    removeMoment,
    comments,
    loadComments,
    addComment,
  }
})
